package com.example.services.impl;

import com.example.bean.Order;
import com.example.bean.Product;
import com.example.services.OrderServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@Service
public class OrderServicesImpl implements OrderServices {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Order createOrder(Integer id, Integer userId) {
        Product product = getProductByIdFromRemote(id);
        Order order = new Order();
        order.setOrderPrice(product.getPrice());
        order.setId(id);
        order.setUserId(userId);
        order.setProductList(Arrays.asList(product));
        return order;
    }

    public Product getProductByIdFromRemote(Integer id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("services-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/products/" + id;
//        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.getForObject(url, Product.class);
    }
}
